// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include <stdio.h>
#include <string.h>

#include <api.h>
#include <qSocket.hpp>

#include <stddef.h>
#include "azure_c_shared_utility/tcpsocketconnection_c.h"


TCPSOCKETCONNECTION_HANDLE tcpsocketconnection_create(void)
{
	return (TCPSOCKETCONNECTION_HANDLE) new qSocketClient();
}

void tcpsocketconnection_set_blocking(TCPSOCKETCONNECTION_HANDLE tcpSocketConnectionHandle, bool blocking, unsigned int timeout)
{

}

void tcpsocketconnection_destroy(TCPSOCKETCONNECTION_HANDLE tcpSocketConnectionHandle)
{
	qSocketClient *tcp = (qSocketClient *)tcpSocketConnectionHandle;
	delete tcp;
}

int tcpsocketconnection_connect(TCPSOCKETCONNECTION_HANDLE tcpSocketConnectionHandle, const char* host, const int port)
{
	TimeLoop t;
	t.Keep();
	qSocketClient *tcp = (qSocketClient *)tcpSocketConnectionHandle;
	tcp->Connect(host, port);
	while (not (tcp->IsConnect() or t.IsOver(2000)))xos::Wait(20);
	return not tcp->IsConnect();
}

bool tcpsocketconnection_is_connected(TCPSOCKETCONNECTION_HANDLE tcpSocketConnectionHandle)
{
	qSocketClient *tcp = (qSocketClient *)tcpSocketConnectionHandle;
	return tcp->IsConnect();
}

void tcpsocketconnection_close(TCPSOCKETCONNECTION_HANDLE tcpSocketConnectionHandle)
{
	qSocketClient *tcp = (qSocketClient *)tcpSocketConnectionHandle;
	tcp->close();
}

int tcpsocketconnection_send(TCPSOCKETCONNECTION_HANDLE tcpSocketConnectionHandle, const char* data, int length)
{
	qSocketClient *tcp = (qSocketClient *)tcpSocketConnectionHandle;
	return tcp->write(data, length);
}

int tcpsocketconnection_send_all(TCPSOCKETCONNECTION_HANDLE tcpSocketConnectionHandle, const char* data, int length)
{
	return tcpsocketconnection_send(tcpSocketConnectionHandle,data,length);
}

int tcpsocketconnection_receive(TCPSOCKETCONNECTION_HANDLE tcpSocketConnectionHandle, char* data, int length)
{
	qSocketClient *tcp = (qSocketClient *)tcpSocketConnectionHandle;
	return tcp->read(data, length, 0);
}

int tcpsocketconnection_receive_all(TCPSOCKETCONNECTION_HANDLE tcpSocketConnectionHandle, char* data, int length)
{
	return tcpsocketconnection_receive(tcpSocketConnectionHandle, data, length);
}
